package com.shuqi.common;

import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.util.EncodingUtils;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.res.AssetManager;

import com.shuqi.common.utils.Log4an;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.model.bean.BookCoverInfo;
import com.shuqi.model.manager.DownLoadBookManager;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.parse.parser.BookCoverParser;
import com.shuqi.model.parse.parser.PayDownCatalogParser;

/**
 * 内置书籍
 * 
 * @author Jianda.Yang
 * 
 * @Date 2014-3-14 上午10:13:08
 */
public class InlayBook {
    private static Context mContext;
    private static SAXParser saxParser;
    private static final String path = "inlayBook/";
    private static String mBids[] = {"74797", "124225", "164620", "3379630"};

    private static String mCids[] = {"133436", "308780", "236456", "256930"};


    /**
     * 获取内置书籍的bid
     * 
     * @return
     */
    public static String[] getInlayBooks() {
        return mBids;
    }

    /** 第一章节内容文件名字 */
    private static String mAssetsBookContents[] = {"133436.sqc", "308780.sqc", "236456.sqc",
            "256930.sqc"};

    private static String mBookCover = "book_cover.xml";// 书籍信息文件
    private static String mCatalog = "chapter_list.xml";// 目录文件

    private static String mUid;


    public static synchronized void synInlayBook(Context context) {
        mContext = context;
        init();
        copyAssest();
        saveBookCoverInfo();
        saveCatalog();
    }

    private static AssetManager mAssetManager;

    private static void init() {
        mUid = MyAccountManager.getInstance(mContext).getUserId();
        saxParser = getSAXParser();
        mAssetManager = mContext.getAssets();
    }

    /**
     * 拷贝文件
     */
    private static void copyAssest() {

        for (int i = 0; i < mBids.length; i++) {
            String ss = getFromAssets(path + mBids[i] + "/" + mAssetsBookContents[i]);
            boolean isWrite =
                    DownLoadBookManager.writeChapterFile(null, mBids[i], mUid, mCids[i], ss);
            if (!isWrite) {
                break;
            }
        }

    }

    private static void saveBookCoverInfo() {
        int maxOid = 0;
        for (int i = 0; i < mBids.length; i++) {
            try {
                BookCoverParser bookCoverParser = new BookCoverParser();
                InputStream is = mAssetManager.open(path + mBids[i] + "/" + mBookCover);
                saxParser.parse(is, bookCoverParser);
                maxOid = Integer.parseInt(bookCoverParser.getParsedData().getMaxOid());
                saveBookInfoData(bookCoverParser.getParsedData(), maxOid);
                saveBookMark(bookCoverParser, i);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }


    /**
     * 保存书籍信息
     */
    private static void saveBookInfoData(BookCoverInfo coverInfo, int oid) {
        if (coverInfo != null) {
            BookInfo info = new BookInfo();
            info.setUserId(mUid);
            info.setBookAuthorName(coverInfo.getAuthor());
            info.setBookId(coverInfo.getBookId());
            info.setBookName(coverInfo.getBookName());
            Log4an.i("yjd", "内置书籍：" + info.getBookName());
            info.setBookType(coverInfo.getBookType());
            info.setBookCoverImgUrl(coverInfo.getImageUrl());
            info.setBookUpdateTime(System.currentTimeMillis());
            info.setBookIntro(coverInfo.getDescription());
            info.setBookMaxOid(oid);
            if (coverInfo.getPaid() != null) {
                info.setBookPayState(Integer.valueOf(coverInfo.getPaid()));
            }
            info.setBookPayMode(coverInfo.getPayMode());
            if (coverInfo.getPrice() != null) {
                info.setBookPrice(Float.valueOf(coverInfo.getPrice()));
            }
            if (coverInfo.getBookState() != null) {
                info.setBookStatus(coverInfo.getBookState());
            }
            info.setSourceType(BookInfo.SOURCE_TYPE_SHUQI);
            info.setBookHistoryState(BookInfo.UNIN_HISTORY);// 需要加入到浏览历史里
            BookInfoDao.getInstance().saveOrUpdateBookInfo(info);
        }
    }

    /**
     * 保存目录
     */
    private static void saveCatalog() {
        for (int i = 0; i < mBids.length; i++) {
            try {
                PayDownCatalogParser catalogParser = new PayDownCatalogParser(mBids[i], null, mUid);
                InputStream is = mAssetManager.open(path + mBids[i] + "/" + mCatalog);
                saxParser.parse(is, catalogParser);
                for (int j = 0; j < catalogParser.getParsedData().getInfos().size(); j++) {
                    if (mCids[i].equals(catalogParser.getParsedData().getInfos().get(j)
                            .getChapterId())) {
                        catalogParser.getParsedData().getInfos().get(j)
                                .setDownloadState(BookCataLog.HAS_DOWN);
                    }
                }
                BookCataLogDao.getInstance().saveOrUpdateCatalog(mUid, mBids[i], null,
                        catalogParser.getParsedData().getInfos());
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }

    }

    private static void saveBookMark(BookCoverParser bookCoverParser, int i) {
        if (bookCoverParser == null) {
            return;
        }
        BookMarkInfo info = new BookMarkInfo();
        info.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
        info.setBookName(bookCoverParser.getParsedData().getBookName());
        info.setSourceId("");
        info.setBookId(bookCoverParser.getParsedData().getBookId());
        info.setChapterId(mCids[i]);
        info.setBookReadByte(0);
        info.setBookTotalByte(0);
        info.setChapterName("" + i);
        info.setPayMode("0");
        info.setUserId(mUid);
        info.setBookCoverImgUrl(bookCoverParser.getParsedData().getImageUrl());
        info.setPercent("0");
        info.setTotalChapter(Integer.parseInt((bookCoverParser.getParsedData().getMaxOid())));
        BookMarkInfoDao.getInstance().saveBookMark(info);
    }



    private static SAXParser getSAXParser() {
        if (saxParser == null) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                saxParser = spf.newSAXParser();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
        }
        return saxParser;
    }

    /**
     * 从assets 文件夹中获取文件并读取数据
     * 
     * @param fileName
     * @return
     */
    private static String getFromAssets(String fileName) {
        String result = "";
        try {
            InputStream in = mContext.getResources().getAssets().open(fileName);
            int lenght = in.available();
            byte[] buffer = new byte[lenght];
            in.read(buffer);
            result = EncodingUtils.getString(buffer, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
